﻿using System;
using SKYPE4COMLib;

namespace libSkype
{
    public class SkypeWrapperEventArgs : EventArgs
    {
        public string Sender { get; set; }
        public string Message { get; set; }
        public int MessageId { get; set; }
    }

    public class SkypeWrapper : IDisposable
    {
        private Chat _chat;
        private SkypeClass _skype;

        public SkypeWrapper()
        {
            _skype = new SkypeClass();
            if (!_skype.Client.IsRunning)
            {
                _skype.Client.Start(true, true);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            _skype = null;
        }

        #endregion

        public void StartChat(string buddy)
        {
            _skype.MessageStatus += OnMessageStatus;
            if (string.IsNullOrEmpty(buddy) || _skype.get_User(buddy) == null)
            {
                throw new ArgumentOutOfRangeException(buddy);
            }

            try
            {
                _chat = _skype.CreateChatWith(buddy);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Could not start chat with buddy: {0}", buddy), ex);
            }
        }

        private void OnMessageStatus(ChatMessage pmessage, TChatMessageStatus status)
        {
            if (pmessage.Chat.Name == _chat.Name && status == TChatMessageStatus.cmsReceived)
            {
                if (OnMessageReceived != null)
                    OnMessageReceived(this, new SkypeWrapperEventArgs
                                                {
                                                    MessageId = pmessage.Id,
                                                    Message = pmessage.Body,
                                                    Sender = pmessage.Sender.Handle
                                                });
            }
        }

        public void SendMessage(string text)
        {
            _chat.SendMessage(text);
        }

        public event EventHandler<SkypeWrapperEventArgs> OnMessageReceived;
    }
}